package com.rabbiter.market.service.pay.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.rabbiter.market.common.config.AlipayConfig;
import com.rabbiter.market.common.util.QRUtil;
import com.rabbiter.market.domain.sale.sale_records.SaleRecords;
import com.rabbiter.market.service.pay.PayService;
import com.rabbiter.market.service.sale_management.sale_records.ISaleRecordsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: longxianghang
 * @date: 2025/3/21 16:03
 * @description:
 */
@Service
public class AliPayServiceImpl implements PayService {

    @Resource
    private AlipayConfig alipayConfig;

    @Resource
    private ISaleRecordsService saleRecordsService;

    @Override
    public Map<String, String> alipay(SaleRecords saleRecords, HttpServletResponse httpResponse) {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()
        );
        // 构造请求参数以调用接口
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        // 设置请求回调地址
        request.setNotifyUrl(alipayConfig.getNotifyUrl());

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

        // 设置商户门店编号
        model.setStoreId("ZLF_001");

        // 设置业务扩展参数
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088511833207846");
        extendParams.setSpecifiedSellerName("深圳泽立方信息科技有限公司");
        extendParams.setCardType("S0JP0000");
        model.setExtendParams(extendParams);

        // 设置订单标题
        model.setSubject("深圳泽立方信息科技有限公司");

        // 支付订单过期时间
        model.setTimeoutExpress(alipayConfig.getTimeoutExpress());

        // 设置商户操作员编号
        model.setOperatorId("001");

        // 设置产品码
        model.setProductCode("FACE_TO_FACE_PAYMENT");

        // 设置订单附加信息
        model.setBody("desc");

        // 设置订单包含的商品列表信息
        List<GoodsDetail> goodsDetailList =  new ArrayList<GoodsDetail>();
        AtomicReference<Double> totalAmount = new AtomicReference<>(0D);
        saleRecords.getDetailSaleRecords().forEach(detailSaleRecords -> {
            GoodsDetail goodsDetail = new GoodsDetail();
            goodsDetail.setGoodsName(detailSaleRecords.getGoodsName());
            goodsDetail.setQuantity(detailSaleRecords.getGoodsNum());
            goodsDetail.setPrice(String.valueOf(detailSaleRecords.getGoodsPrice()));
            goodsDetail.setGoodsId(String.valueOf(detailSaleRecords.getGoodsId()));
            goodsDetailList.add(goodsDetail);

            totalAmount.updateAndGet(v -> v + detailSaleRecords.getGoodsNum() * detailSaleRecords.getGoodsPrice());
        });


//        goodsDetail0.setGoodsCategory("34543238");
//        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
//        goodsDetail0.setShowUrl(alipayConfig.getNotifyUrl());
//        goodsDetail.add(goodsDetail0);
        model.setGoodsDetail(goodsDetailList);

        // 设置商户的原始订单号
        model.setMerchantOrderNo(saleRecords.getCn());

        // 设置可打折金额
        //model.setDiscountableAmount("80.00");

        // 设置商户订单号
        model.setOutTradeNo(saleRecords.getCn());

        // 设置订单总金额
        model.setTotalAmount(String.valueOf(String.format("%.2f", totalAmount.get())));

        // 设置商户传入业务信息
        BusinessParams businessParams = new BusinessParams();
        businessParams.setMcCreateTradeIp("127.0.0.1");
        model.setBusinessParams(businessParams);

        // 设置卖家支付宝用户ID
        model.setSellerId("2088721035348681");

        // 设置商户机具终端编号
        model.setTerminalId("NJ_T_001");

        request.setBizModel(model);

        // 支付完成后自动跳转本地页面的路径
        request.setReturnUrl("http://localhost:8080/?");

        Map<String, String> map = new HashMap<>();
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            System.out.println(response);

            String content = response.getQrCode();
            // 将响应的结果返回给浏览器
            if (response.isSuccess()) {
                System.out.println("调用成功");
                // 返回二维码
                if(null != httpResponse) {
                    QRUtil.createCodeToOutputStream(content, httpResponse.getOutputStream());
                }

                map.put("out_trade_no", response.getOutTradeNo());
                map.put("code", response.getCode());

                // 返回form表单 ---前端页面暂时未正确显示
//                String form = alipayClient.pageExecute(request).getBody();
//                System.out.println("表单页面" + form);
//                servletResponse.setContentType("text/html;charset=" + alipayConfig.getCharset());
//                servletResponse.getWriter().write(form); // 直接将完整的表单输出到页面
//                servletResponse.getWriter().flush();
//                servletResponse.getWriter().close();
            } else {
                System.out.println("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
            }


            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("支付宝支付接口调用异常");
        }
    }

    public void alipayNotify(HttpServletRequest request) {
        Map< String , String > params = new HashMap< String , String >();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String [])requestParams.get(name);
            String valueStr = "";
            for(int i = 0;i < values.length;i ++ ){
                valueStr =  (i==values.length-1)?valueStr + values [i]:valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            System.out.println(name + ":" + valueStr);
            params.put (name,valueStr);
        }
        //调用SDK验证签名
        //公钥验签示例代码
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
            //公钥证书验签示例代码
            //   boolean flag = AlipaySignature.rsaCertCheckV1(params,alipayPublicCertPath,"UTF-8","RSA2");

            if (signVerified) {
                // TODO 验签成功后
                //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success

                // 调用orderService修改订单支付状态
                SaleRecords saleRecords = saleRecordsService.getSaleRecordsByOutTradeNo(params.get("out_trade_no"));
                saleRecords.setPayStatus(20);
                saleRecordsService.updateSaleRecords(saleRecords);
            } else {
                // TODO 验签失败则记录异常日志，并在response中返回fail.
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public AlipayTradeQueryResponse queryOrder(String outTradeNo, String tradeNo, String orgPid, List<String> queryOptions) {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()
        );

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(outTradeNo);

        // 设置支付宝交易号
//        model.setTradeNo("2014112611001004680 073956707");

        // 设置查询选项
//        List<String> queryOption = new ArrayList<String>();
//        queryOption.add("trade_settle_info");
//        model.setQueryOptions(queryOptions);

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        try {
            AlipayTradeQueryResponse response  = alipayClient.execute(request);
            System.out.println(response.getTradeStatus());
            System.out.println(response.getCode());

            if (response.isSuccess()) {
                System.out.println("调用成功");
                return response;
            } else {
                System.out.println("调用失败");

                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
